﻿using Prism.Mvvm;
using Prism.Regions;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using MyTodo.Common.Models;
using Prism.Commands;
using MyTodo.Extensions;

namespace MyTodo.ViewModels;

public class MainViewModel : BindableBase
{
    private readonly IRegionManager _regionManager;

    private IRegionNavigationJournal? _navigationJournal;

    public MainViewModel(IRegionManager regionManager)
    {
        MenuBars = new ObservableCollection<MenuBar>();
        CreateMenuBar();
        _regionManager = regionManager;
        NavigateCommand = new DelegateCommand<MenuBar>(Navigate);
        GoBackCommand = new DelegateCommand(() =>
        {
            if (_navigationJournal?.CanGoBack ?? false)
            {
                _navigationJournal?.GoBack();
            }
        });
        GoForwardCommand = new DelegateCommand(() =>
        {
            if (_navigationJournal?.CanGoForward ?? false)
            {
                _navigationJournal?.GoForward();
            }
        });
        GoIndexCommand = new DelegateCommand(() => {
            Navigate(new MenuBar { NameSpace = "IndexView" });
        });
    }

    public DelegateCommand<MenuBar> NavigateCommand { get; private set; }
    public DelegateCommand GoBackCommand { get; private set; }
    public DelegateCommand GoForwardCommand { get; private set; }
    public DelegateCommand GoIndexCommand { get; private set; }

    public ObservableCollection<MenuBar>? MenuBars { get; set; }

    private void CreateMenuBar()
    {
        MenuBars?.Add(new MenuBar() { Icon = "Home", Title = "首页", NameSpace = "IndexView" });
        MenuBars?.Add(new MenuBar() { Icon = "CalendarTextOutline", Title = "待办事项", NameSpace = "ToDoView" });
        MenuBars?.Add(new MenuBar() { Icon = "Notebook", Title = "备忘录", NameSpace = "MemoView" });
        MenuBars?.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingView" });
    }

    private void Navigate(MenuBar menuBar)
    {
        if (menuBar == null || string.IsNullOrWhiteSpace(menuBar.NameSpace))
            return;
        _regionManager.RequestNavigate(PrismManager.MainViewRegionName, menuBar.NameSpace, back =>
        {
            if (back.Result ?? false)
            {
                _navigationJournal = back.Context.NavigationService.Journal;
            }
        });
    }

}
